package com.qili.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.entity.exam.ExExam;
import com.qili.entity.exam.ExQuAnswer;
import com.qili.entity.exam.ExStuExamCopy;
import com.qili.entity.exam.ExStuExamDetail;
import com.qili.entity.exam.dto.ExExamDTO;
import com.qili.entity.exam.dto.ExQuestionDTO;
import com.qili.entity.exam.dto.ExStuExamCopyDTO;
import com.qili.mapper.exam.ExQuestionMapper;
import com.qili.mapper.exam.ExStuExamCopyMapper;
import com.qili.service.exam.ExExamService;
import com.qili.service.exam.ExQuAnswerService;
import com.qili.service.exam.ExStuExamDetailService;
import com.qili.util.DateUtil;
import com.qili.util.JsonUtil;
import com.qili.util.ReType;
import com.qili.util.StringUtil;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.spring.web.json.Json;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author zhangxiaopeng
 * @date 2021-08-31
 * @description评分
 */
@Controller
@RequestMapping("/give/mark")
public class giveAMarkController {
    @Autowired
    ExStuExamCopyMapper exStuExamCopyMapper;
    @Autowired
    ExStuExamDetailService exStuExamDetailService;
    @Autowired
    ExQuestionMapper exQuestionMapper;
    @Autowired
    ExQuAnswerService exQuAnswerService;
    @Autowired
    ExExamService exExamService;

    /**
     * @Description:评分页面跳转
     * @param model
     * @Date:15:01 2021-08-23
     */
    @RequestMapping("/giveMark")
    public String giveMark(Model model, String examId){
        model.addAttribute("examId",examId);
        return "/examList/giveMarkList";
    }

    /**
    * @Description:评分列表
    * @param dto
        * @param page
        * @param limit
    * @Date:10:51 2021-08-31
    */
    @GetMapping(value = "/selectExamList")
    @ResponseBody
    public ReType selectExamList(ExStuExamCopyDTO dto,int page,int limit){
        List<ExStuExamCopyDTO> examCopyList=new ArrayList<>();
        Page<ExStuExamCopyDTO> tPage = PageHelper.startPage(page, limit);
        try{
            examCopyList=exStuExamCopyMapper.selectExamList(dto);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), examCopyList);
    }

    /**
     * @Description: 日志留痕
     * @param dto
     * @param page
     * @param limit
     * @Date:10:51 2021-08-31
     */
    @GetMapping(value = "/selectExamTimeList")
    @ResponseBody
    public ReType selectExamTimeList(ExStuExamCopyDTO dto,int page,int limit){
        List<ExStuExamCopyDTO> examCopyList=new ArrayList<>();
        Page<ExStuExamCopyDTO> tPage = PageHelper.startPage(page, limit);
        try{
            if ("userName".equals(dto.getField())){
                dto.setField("userName");
            }else {
                dto.setField(humpToUnderline(dto.getField()));
            }

            examCopyList=exStuExamCopyMapper.selectExamTimeList(dto);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), examCopyList);
    }

    //排序字段处理
    public static String humpToUnderline(String name) {
        StringBuilder result = new StringBuilder();
        if (name != null && name.length() > 0) {
            // 将第一个字符处理成大写
            result.append(name.substring(0, 1).toUpperCase());
            // 循环处理其余字符
            for (int i = 1; i < name.length(); i++) {
                String s = name.substring(i, i + 1);
                // 在大写字母前添加下划线
                if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
                    result.append("_");
                }
                // 其他字符直接转成大写
                result.append(s.toUpperCase());
            }
        }
        return result.toString();
    }

    /**
    * @Description:评分跳转
    * @param esec
        * @param model
    * @Date:9:33 2021-09-01
    */
    @RequestMapping("/giveAMark")
    public String giveAMark(ExStuExamCopy esec, Model model){
        //查询试题
        Map map=new HashMap<>();
        map.put("paperId",esec.getPaperId());
        List<ExQuestionDTO> question=exQuestionMapper.selectQuestion(map);
        //查询问题下的答案
        for(int i=0;i<question.size();i++){
            //题目的答案
            Example example=new Example(ExQuAnswer.class);
            Example.Criteria criterias = example.createCriteria();
            criterias.andEqualTo("quId",question.get(i).getQuId());
            example.setOrderByClause("serial");
            List<ExQuAnswer> exQuAnswer=exQuAnswerService.selectByExample(example);
            StringJoiner join=new StringJoiner(",");
            for(int j=0;j<exQuAnswer.size();j++){
                if("1".equals(exQuAnswer.get(j).getIsRight())){
                    join.add(parseHtml(exQuAnswer.get(j).getAnswerContent()));
                }
            }
            question.get(i).setAnswer(join.toString());
            //查询考生明细表
            ExStuExamDetail examDetail=new ExStuExamDetail();
            examDetail.setExStuExamId(esec.getStuExamId());
            examDetail.setQuId(question.get(i).getQuId());
            ExStuExamDetail detail=exStuExamDetailService.selectOne(examDetail);
            if (null == detail) {
                question.get(i).setOwnAnswer("");
            } else {
                question.get(i).setOwnAnswer(detail.getAnswer());
            }
            question.get(i).setAnalysis(parseHtml(question.get(i).getAnalysis()));
        }
        model.addAttribute("stuExamId",esec.getStuExamId());
        model.addAttribute("examId",esec.getExamId());
        model.addAttribute("st",question);
        return "/examList/giveAMark";
    }


    //处理富文本数据
    public String parseHtml(String html) {
        if(html == null || html == "") {
            return html = "空";
        }else {
            html = html.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");
            return html;
        }
    }

    /**
    * @Description:评分操作
    * @param dto
    * @Date:14:15 2021-09-01
    */
    @PostMapping("/updateScore")
    @ResponseBody
    @RequiresRoles("ksgly")
    public JsonUtil updateScore(ExStuExamCopyDTO dto){
        JsonUtil json=new JsonUtil();
        try{
            //维护考试明细表
            List<ExStuExamDetail> examDetails=dto.getDetail();
            Integer score=0;
            if(examDetails!=null && examDetails.size()>0){
                for(int i=1;i<examDetails.size();i++){
                    ExStuExamDetail examDetail=new ExStuExamDetail();
                    examDetail.setQuId(examDetails.get(i).getQuId());
                    examDetail.setExStuExamId(dto.getStuExamId());
                    examDetail=exStuExamDetailService.selectOne(examDetail);
                    examDetail.setScore(examDetails.get(i).getScore());
                    exStuExamDetailService.updateByPrimaryKeySelective(examDetail);
                    score+=Integer.parseInt(examDetails.get(i).getScore());
                }
            }
            ExExam exam=exExamService.selectByPrimaryKey(dto.getExamId());
            //维护考生考试表
            ExStuExamCopy examCopy=new ExStuExamCopy();
            examCopy.setStuExamId(dto.getStuExamId());
            examCopy.setIsMark("1");
            examCopy.setScore(score.toString());
            //判断是否及格
            if(score>=Integer.parseInt(exam.getPassScore())){
                examCopy.setIsJg("1");
            }else{
                examCopy.setIsJg("0");
            }
            exStuExamCopyMapper.updateByPrimaryKeySelective(examCopy);
            json.setFlag(true);
        }catch (Exception e){
            json.setFlag(false);
            e.printStackTrace();
        }
        return json;
    }

    /**
    * @Description:重置分数
    * @param ids
    * @Date:15:00 2021-09-01
    */
    @GetMapping("/updateReset")
    @ResponseBody
    public JsonUtil updateReset(String ids){
        JsonUtil json=new JsonUtil();
        try{
            String[] arr=ids.split(",");
            for(int j=0;j<arr.length;j++) {
                //重置考生考试表
                ExStuExamCopy examCopy = new ExStuExamCopy();
                examCopy.setStuExamId(arr[j]);
                examCopy.setIsMark("0");
                examCopy.setIsJg("");
                examCopy.setScore("");
                exStuExamCopyMapper.updateByPrimaryKeySelective(examCopy);
                //重置考生分数
                ExStuExamDetail examDetail = new ExStuExamDetail();
                examDetail.setExStuExamId(arr[j]);
                List<ExStuExamDetail> examDetails = exStuExamDetailService.select(examDetail);
                if (examDetails != null && examDetails.size() > 0) {
                    for (int i = 0; i < examDetails.size(); i++) {
                        examDetails.get(i).setScore("0");
                        exStuExamDetailService.updateByPrimaryKeySelective(examDetails.get(i));
                    }
                }
            }
            json.setFlag(true);
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(false);
        }
        return json;
    }

    /**
    * @Description:删除
    * @param stuExamId
    * @Date:16:12 2021-09-01
    */
    @GetMapping("/updateDel")
    @ResponseBody
    public JsonUtil updateDel(String stuExamId){
        JsonUtil json=new JsonUtil();
        try{
            ExStuExamCopy examCopy=new ExStuExamCopy();
            examCopy.setStuExamId(stuExamId);
            examCopy.setState("000");
            if(exStuExamCopyMapper.updateByPrimaryKeySelective(examCopy)>0){
                json.setFlag(true);
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(false);
        }
        return json;
    }

    /**
    * @Description:导出
    * @param ids
        * @param response
    * @Date:17:35 2021-09-01
    */
    @GetMapping("/export")
    public void export(String[] ids, HttpServletResponse response){
        String  fileName="评分数据"+DateUtil.getCurrentDateNoSpliter();
        HashMap map=new HashMap();
        ExStuExamCopyDTO dto=new ExStuExamCopyDTO();
        dto.setExamIds(ids);
        //选中的评分数据
        List<ExStuExamCopyDTO> examCopyList=exStuExamCopyMapper.selectExamList(dto);
        for(int i=0;i<examCopyList.size();i++){
            if("1".equals(examCopyList.get(i).getIsMark())){
                examCopyList.get(i).setIsMark("已评分");
            }else{
                examCopyList.get(i).setIsMark("未评分");
            }
            if(StringUtil.isNotBlank(examCopyList.get(i).getIsJg())){
                if("1".equals(examCopyList.get(i).getIsJg())){
                    examCopyList.get(i).setIsJg("是");
                }else{
                    examCopyList.get(i).setIsJg("否");
                }
            }
        }
        map.put("examLists",examCopyList);
        try {
            ExcelExportUtilEX.exportExcel(response,map,fileName,"KS003");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
